import React, {useEffect, useState, forwardRef, useImperativeHandle, useMemo} from 'react';
import PageModule from "@/components/PageModule.tsx";
import {Form, Row, Table, Button, message} from "antd";
import CycleForm from "@/components/DynamicSearchForm/CycleForm.tsx";
import PageActionBar from "@/components/PageActionBar.tsx";
import {getDicOnCode} from "@/utils/dicAll.ts";
import {querySaleListForProject} from "@/axios/apis.ts";

const AgentInfo = forwardRef(({carAgentInfo, projectCode, policyDisabled}, ref) => {
    useImperativeHandle(ref, () => ({
        verifyTheForm: () => {
            setShow(false)
            if (!dataSource.length) {
                message.warning('代理人信息最少一条')
                return false
            }
            if (dataSource.length === 1 && dataSource[0].mainFlag != 1) {
                message.warning('仅有一个经纪人时，主出单人必须选择“是”，经纪人顺序必须选择“1”');
                return false
            }
            return dataSource
        }
    }))
    const [AgentForm] = Form.useForm()
    const [rowIndx, setRowIndx] = useState(undefined)
    const [dataSource, setDataSource] = useState([])
    const [formDisabled, setFormDisablede] = useState(false)
    const btnList = [
        {
            name: '新增',
            type: 'primary',
            onClick: () => {
                if (!projectCode) return message.error('请选择项目名称')
                setShow(true)
                // let code = getPojectCode()
                //  console.log(code,'code')
            }
        }
    ]
    const columns = [
        {
            title: '操作',
            key: 'action',
            render: (_, record, index) => (
                <div className="table-options">
                    <span className="operation_style"
                          onClick={() => lookOrEdit('details', record, undefined)}>查看</span>
                    {!policyDisabled?<span className="operation_style" onClick={() => lookOrEdit('edit', record, index)}>修改</span>:null}
                    {!policyDisabled?<span className="operation_style danger" onClick={() => deleteRow(index)}>删除</span>:null}
                </div>
            ),
            width: 140,
            align:'center'
        },
        {title: '代理人人姓名', dataIndex: 'agentName', key: 'agentName'},
        {title: '代理人工号', dataIndex: 'agentCode', key: 'agentCode'},
        {title: '代理人执业证编号', dataIndex: 'grantCode', key: 'grantCode'},
        {title: '机构名称', dataIndex: 'orgName', key: 'orgName'},
        {
            title: '主出单人', dataIndex: 'mainFlag', key: 'mainFlag',
            render: (value) => <>{value === "1" ? "是" : value === "0" ? "否" : ""}</>,
        },
        {title: '经纪人顺序', dataIndex: 'agentOrder', key: 'agentOrder'},
    ]
    const [formFields, setFormFields] = useState([
        {
            type: 'select',
            name: 'agentCode',
            label: '代理人姓名',
            placeholder: '请选择',
            options: [],
            rules: [{required: true, message: '请选择代理人'}],
            fieldNames: {
                label: 'saleName',
                value: 'saleCode'
            },
            onChange: (value) => {
                if (!value) return
                const item = formFields[0].options.find(ite => ite.saleCode === value)
                if (!item) return;
                console.log(item, 'agentName')
                AgentForm.setFieldValue('agentName', item.saleName)
                AgentForm.setFieldValue('grantCode', item.grantCode)
                AgentForm.setFieldValue('orgName', item.orgName)
            }
        },
        {
            type: 'input',
            name: 'agentCode',
            label: '代理人工号',
            disabled: true,
        },
        {
            type: 'input',
            name: 'grantCode',
            label: '代理人执业证编号',
        },
        {
            type: 'input',
            name: 'orgName',
            label: '机构名称',
            disabled: true,
        },
        {
            type: 'select',
            name: 'mainFlag',
            label: '主出单人',
            placeholder: '请选择',
            options: getDicOnCode('SYS.ISNOT'),
            rules: [{required: true, message: '请选择主出单人'}],
            onChange: (value) => {
                const val = value === "1" ? 1 : undefined
                AgentForm.setFieldValue('agentOrder', val)
                const list = [...formFields]
                list[5].disabled = val === 1
                setFormFields(list)
            }
        },
        {
            type: 'select',
            name: 'agentOrder',
            label: '经纪人顺序',
            placeholder: '请选择',
            options: Array.from({length: 16}, (_, i) => {
                return {
                    dicItemName: i + 1,
                    dicItemCode: i + 1
                }
            }),
            rules: [{required: true, message: '请选择经纪人顺序'}],
            disabled: false
        }
    ])
    const [show, setShow] = useState(false)
    // 查看修改
    const lookOrEdit = (type, record, index): void => {
        setRowIndx(index)
        AgentForm.setFieldsValue(record)
        setShow(true)
        setFormDisablede(type === 'details')
    }
    // 删除
    const deleteRow = (index: number) => {
        setDataSource(dataSource.filter((_, i) => i !== index))
    }
    const cancel = () => {
        setShow(false)
        AgentForm.resetFields()
        setFormDisablede(false)
    }
    const onFinish = (values: any) => {
        console.log('Success:', values);
        const index = dataSource.findIndex(item => item.agentCode === values.agentCode)
        if (index > -1 && index !== rowIndx) {
            return message.warning('已存在当前顺序经纪人')
        }
        const item = formFields[0].options.find(ite => ite.saleCode === values.agentCode)
        if (item) {
            values = {...values, agentName: item.saleName}
        }
        if (rowIndx !== undefined) {
            const list = [...dataSource]
            list[rowIndx] = values
            setDataSource(list)
        } else {
            setDataSource([...dataSource, values]);
        }
        setShow(false)
        AgentForm.resetFields()
    }
    useEffect(() => {
        if (!projectCode) return
        querySaleListForProject({projectCode}).then(res => {
            if (+res.code === 200) {
                const list = [...formFields]
                list[0].options = res.data
                setFormFields(list)
            }
        })
    }, [projectCode]);
    useEffect(() => {
        if (!carAgentInfo || !carAgentInfo.length) return
        setDataSource(carAgentInfo)
    }, [carAgentInfo])
    return (
        <PageModule title="代理人信息" btns={!policyDisabled?<PageActionBar btnList={btnList} inline />:null}>
            <Table dataSource={dataSource} columns={columns} bordered={true} size="middle" pagination={false} />
            <Form
                layout="horizontal"
                autoComplete="off"
                labelCol={{span: 8}}
                wrapperCol={{span: 16}}
                form={AgentForm}
                style={{marginTop: 20, display: show ? 'block' : 'none'}}
                onFinish={onFinish}
                initialValues={
                    {countryCode: '008zg'}
                }
                disabled={formDisabled}
            >
                <Row>
                    <CycleForm fields={formFields} />
                </Row>
                <Form.Item wrapperCol={{offset: 2}}>
                    <Button className="mr15" type="primary" htmlType="submit">保存</Button>
                    <Button onClick={cancel} disabled={false}>取消</Button>
                </Form.Item>
            </Form>
        </PageModule>
    );
})
export default AgentInfo;